//
//  KDHomeListDataTool.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/6/23.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "KDHomeListDataTool.h"
#import "FMDB.h"
#import "KDHomeListPageCellModel.h"
@implementation KDHomeListDataTool
static FMDatabase *_db;
+ (void)initialize
{
    //1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"homeListDatas.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    //2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_homeListDatas (id integer PRIMARY KEY AUTOINCREMENT, KDHomeListPageCellModel blob NOT NULL,idstr text NOT NULL UNIQUE, parentID text NOT NULL);"];
}
/**
 *  根据请求参数读取相应的列表数据
 *
 *  @param param 请求参数
 *
 *  @return 返回的列表数据
 */
+ (NSArray *)homeListDatasWithParam:(NSDictionary *)param{
    NSString *sql = [NSString stringWithFormat:@"SELECT *FROM t_homeListDatas WHERE idstr = %@, parentID = %@ LIMIT 0，10", param[@"idstr"], param[@"parentID"]];
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *datas = [NSMutableArray array];
    while (set.next) {
        NSData *data = [set objectForColumnName:@"KDHomeListPageCellModel"];
        KDHomeListPageCellModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [datas addObject:model];
    }
    if (!datas.count) {
        return nil;}
    return datas;
}

+ (void)saveHomeListDatasWith:(NSArray *)datas
{
    for (KDHomeListPageCellModel *model in datas) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        [_db executeUpdateWithFormat:@"replace into t_baseboard (KDHomeListPageCellModel, idstr, parentID) VALUES (%@, %@, %@);", data, model.idstr, model.parentID];
    }
}
@end
